package com.xqboss.web.controller.consumer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xqboss.apps.constant.Config;
import com.xqboss.apps.domain.consumer.ConsumerTeamGainRule;
import com.xqboss.apps.domain.consumer.ConsumerTeamGiveRecord;
import com.xqboss.apps.domain.consumer.ConsumerTeamMember;
import com.xqboss.apps.dto.PageDto;
import com.xqboss.apps.dto.consumer.ConsumerTeamDto;
import com.xqboss.apps.dto.consumer.WebConsumerTeamGainRuleDto;
import com.xqboss.apps.dto.consumer.WebGainRuleDto;
import com.xqboss.apps.service.consumer.ConsumerTeamGainRuleService;
import com.xqboss.apps.service.consumer.ConsumerTeamGiveRecordService;
import com.xqboss.apps.service.consumer.ConsumerTeamMemberService;
import com.xqboss.apps.service.consumer.ConsumerTeamService;
import com.xqboss.apps.vo.consumer.ConsumerTeamVo;
import com.xqboss.apps.vo.consumer.TeamCheckRecordVo;
import com.xqboss.apps.vo.team.WebConsumerTeamMemberFamilyVo;
import com.xqboss.apps.vo.user.ConsumerTeamGiveRecordVo;
import com.xqboss.common.annotation.Log;
import com.xqboss.common.annotation.RepeatSubmit;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.enums.BusinessType;
import com.xqboss.common.utils.LocalDateUtils;
import com.xqboss.system.domain.SysConfig;
import com.xqboss.system.mapper.SysConfigMapper;
import com.xqboss.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * @author Administrator
 */

@Api(tags = {"队伍管理"})
@RestController
@RequestMapping("/web/team")
public class WebConsumerTeamController extends BaseController {

    @Autowired
    private ConsumerTeamService consumerTeamService;
    @Autowired
    private ConsumerTeamGainRuleService consumerTeamGainRuleService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private SysConfigMapper configMapper;
    @Autowired
    private ConsumerTeamMemberService consumerTeamMemberService;
    @Autowired
    private ConsumerTeamGiveRecordService consumerTeamGiveRecordService;

    @PreAuthorize("@ss.hasPermi('web:team:list-page')")
    @ApiOperation("队伍列表")
    @PostMapping("/list-page")
    public R list(@RequestBody ConsumerTeamDto dto) {
        dto.startPage();
        List<ConsumerTeamVo> vo = consumerTeamService.selectList(dto);
        return R.ok(vo);
    }

    @PreAuthorize("@ss.hasPermi('web:team:info')")
    @ApiOperation("队伍详情")
    @GetMapping("/info/{teamId}")
    public R<TeamCheckRecordVo> info(@PathVariable("teamId")
                                     @ApiParam(value = "队伍主键id", required = true)
                                     @NotNull(message = "队伍id不能为空")
                                     Integer teamId) {
        return consumerTeamService.info(teamId);
    }

    @PreAuthorize("@ss.hasPermi('web:team:info:members')")
    @ApiOperation("队伍详情-成员信息")
    @GetMapping("/info-members")
    public R<List<WebConsumerTeamMemberFamilyVo>> infoMembers(ConsumerTeamDto params) {
        List<WebConsumerTeamMemberFamilyVo> vo = consumerTeamMemberService.infoMembers(params);
        return R.ok(vo);
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @PreAuthorize("@ss.hasPermi('web:team:delete')")
    @ApiOperation("解散队伍")
    @GetMapping("/delete/{teamId}")
    @Log(title = "队伍", businessType = BusinessType.DELETE)
    public R delete(@PathVariable("teamId")
                    @ApiParam(value = "队伍主键id", required = true)
                    @NotNull(message = "队伍id不能为空")
                    Integer teamId) {
        //解散所有成员
        consumerTeamMemberService.update(new LambdaUpdateWrapper<ConsumerTeamMember>()
                .set(ConsumerTeamMember::getDelFlag, 1)
                .eq(ConsumerTeamMember::getTeamId, teamId)
        );
        return R.ok(consumerTeamService.removeById(teamId));
    }

    @PreAuthorize("@ss.hasPermi('web:team:gain-rule')")
    @ApiOperation("队伍增益规则列表")
    @PostMapping("/gain-rule")
    public R<WebGainRuleDto> gainRule() {
        List<ConsumerTeamGainRule> list = consumerTeamGainRuleService.list();
        List<WebConsumerTeamGainRuleDto> vo = BeanUtil.copyToList(list, WebConsumerTeamGainRuleDto.class);
        vo.forEach(item -> {
            item.setGain(item.getGain().multiply(new BigDecimal(100)));
        });
        WebGainRuleDto result = new WebGainRuleDto();
        result.setRuleList(vo);
        result.setDescription(sysConfigService.selectConfigByKey(Config.Sys.Punch.队伍增益规则.getKey()));
        result.setConfigKey("sys.team.gainRule");
        return R.ok(result);
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @PreAuthorize("@ss.hasPermi('web:team:gain-add')")
    @ApiOperation("新增队伍增益规则")
    @PostMapping("/gain-add")
    @Log(title = "队伍", businessType = BusinessType.DELETE)
    public R add(@Validated @RequestBody WebGainRuleDto dto) {
        if (ObjUtil.isNotNull(dto.getRuleList())) {
            List<ConsumerTeamGainRule> query = BeanUtil.copyToList(dto.getRuleList(), ConsumerTeamGainRule.class);
            query.forEach(item -> {
                item.setGain(item.getGain().divide(new BigDecimal(100), 2, RoundingMode.UP));
            });
            boolean b = consumerTeamGainRuleService.saveBatch(query);
            if (!b) {
                return R.fail("新增失败");
            }
        }
        if (StrUtil.isNotEmpty(dto.getDescription())) {
            String key = sysConfigService.selectConfigByKey(Config.Sys.Punch.队伍增益规则.getKey());
            if (StrUtil.isBlank(key)) {
                SysConfig config = new SysConfig();
                config.setConfigName("队伍增益规则");
                config.setConfigKey("sys.team.gainRule");
                config.setConfigValue(dto.getDescription());
                config.setConfigType("Y");
                sysConfigService.insertConfig(config);
            }
        }
        return R.ok();
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @PreAuthorize("@ss.hasPermi('web:team:gain-update')")
    @ApiOperation("修改队伍增益规则")
    @PutMapping("/gain-update")
    @Log(title = "队伍", businessType = BusinessType.UPDATE)
    public R update(@RequestBody WebGainRuleDto dto) {
        if (CollUtil.isNotEmpty(dto.getRuleList())) {
            List<ConsumerTeamGainRule> ruleList = BeanUtil.copyToList(dto.getRuleList(), ConsumerTeamGainRule.class);
            try {
                ruleList.forEach(item -> {
                    item.setGain(item.getGain().divide(new BigDecimal(100), 2, RoundingMode.UP));
                    item.setUpdateTime(LocalDateUtils.getCurrentLocalDateTime());
                });
                consumerTeamGainRuleService.saveOrUpdateBatch(ruleList);
            } catch (Exception e) {
                return R.fail("打卡次数重复");
            }
        }
        if (StrUtil.isNotBlank(dto.getConfigKey())) {
            SysConfig config = new SysConfig();
            config.setConfigKey(dto.getConfigKey());
            Long configId = configMapper.selectConfig(config).getConfigId();
            config.setConfigValue(dto.getDescription());
            config.setConfigId(configId);
            sysConfigService.updateConfig(config);
        }
        if (CollUtil.isNotEmpty(dto.getDelIds())) {
            consumerTeamGainRuleService.delByIds(dto.getDelIds());
        }
        return R.ok();
    }

    @PreAuthorize("@ss.hasPermi('web:team:upgrade:give:record')")
    @ApiOperation("转增记录")
    @GetMapping("/give-record")
    public R<List<ConsumerTeamGiveRecordVo>> giveRecord(@Validated PageDto dto) {
        dto.startPage();
        List<ConsumerTeamGiveRecord> list = consumerTeamGiveRecordService.list(new LambdaQueryWrapper<ConsumerTeamGiveRecord>()
                .orderByDesc(ConsumerTeamGiveRecord::getCreateTime));
        List<ConsumerTeamGiveRecordVo> voList = BeanUtil.copyToList(list, ConsumerTeamGiveRecordVo.class);
        return R.ok(voList, list);
    }
}
